#!/usr/bin/env python

# This script retrieves metadata about a cd from cddb, allows you to edit, 
# writes a CUE sheet, rips the cd audio using cdparanoia, encodes to FLAC, 
# then embeds the metadata as FLAC tags.

name = 'AudioArchiver'
ver = '0.1b'

filename = 'AlbumPerformer - AlbumYear - AlbumTitle'
flacdir = '/home/code-breaker/flacs'
cuedir = '/home/code-breaker/flacs/CUEs-Covers' # Cover image will be copied too, if present. If this is '', cue will be deleted.
rip = True
chooseFLAC = True # If rip == False, you can browse for a FLAC file to write tags to
chooseCover = True # If true, browse for image
cddevice = "/dev/cdrom"


import DiscID, CDDB, sys, os, shutil
from sys import argv as argv
from tkFileDialog import askopenfilename
  
workingpath = os.path.abspath(os.path.dirname(argv[0]))
cdrom = None

if len(sys.argv) >= 2:
  cddevice = sys.argv[1]

ripper_options = "--force-cdrom-device " + cddevice + " --force-read-speed 40 1-"

if cddevice:
  cdrom = DiscID.open(cddevice)
else:
  cdrom = DiscID.open()
edit = 'n'
print "Getting disc id in CDDB format...",
disc_id = DiscID.disc_id(cdrom)
print "Disc ID: %08lx Num tracks: %d" % (disc_id[0], disc_id[1])
(query_stat, query_info) = CDDB.query(disc_id)
if query_stat != 200 and query_stat != 210 and query_stat != 211:
  print "failure getting disc info, status %i\nyou must edit metadata manually" % query_stat
  edit = 'y'
else:
  if query_stat != 200:
    print "multiple matches found! Matches are:"
    j = 1
    for i in query_info:
      print "%s. %s" % (str(j), i['title'])
      j = j + 1
    ret = raw_input("Which album? ")
    query_info = query_info[int(ret)-1]
  print ("Querying CDDB for track info on `%s'...\n" % query_info['title']),
  (read_stat, CDDB_Info) = CDDB.read(query_info['category'], query_info['disc_id'])
  if read_stat != 210:
    print "failure getting track info, status: %i\nyou must edit metadata manually" % read_stat
    edit = 'y'

compilation = raw_input("Is this a compilation album? (y/N): ")
if compilation == 'y':
  print "You must add track artists manually"
if edit == 'n':
  edit = raw_input("Would you like to edit the metadata? (y/N): ")
performertitle = CDDB_Info['DTITLE'].split("/")
if edit == 'y':
#  for i in range(0, disc_id[1]):
#    print "%.02d: %s" % (i+1, CDDB_Info['TTITLE' + `i`])
  ret = raw_input("Performer (" + performertitle[0].strip() + "): ")
  if ret != "":
    performertitle[0] = ret
  else:
    performertitle[0] = performertitle[0].strip()
  ret = raw_input("Title (" + performertitle[1].strip() + "): ")
  if ret != "":
    performertitle[1] = ret
  else:
    performertitle[1] = performertitle[1].strip()
  CDDB_Info['DTITLE'] = performertitle[0] + " / " + performertitle[1]
  ret = raw_input("Genre (" + CDDB_Info['DGENRE'] + "): ")
  if ret != "":
    CDDB_Info['DGENRE'] = ret
  ret = raw_input("Year (" + CDDB_Info['DYEAR'] + "): ")
  if ret != "":
    CDDB_Info['DYEAR'] = ret
if edit == 'y' or compilation =='y':
  for i in range(0, disc_id[1]):
    if edit == 'y': 
      ret = raw_input(str(i+1) + ". (" + CDDB_Info['TTITLE' + `i`] + "): ")
      if ret != "":
        CDDB_Info['TTITLE' + `i`] = ret
    if compilation =='y':
      ret = raw_input(str(i+1) + ". ARTIST (" + performertitle[0].strip() + "): ")
      if ret != "":
        CDDB_Info['TARTIST' + `i`] = ret
      else:
        CDDB_Info['TARTIST' + `i`] = performertitle[0].strip()
        
CDDB_Info["REMARK0"] = "GENRE=" + CDDB_Info["DGENRE"]
CDDB_Info["REMARK1"] = "DISCID=" + query_info["disc_id"]
CDDB_Info["REMARK2"] = "YEAR=" + CDDB_Info["DYEAR"]
CDDB_Info["REMARK3"] = "CREATEDBY=" + name + " " + ver
num_remarks = 4
CDDB_Info["NUMREMARKS"] = str(num_remarks)
ret = raw_input("Would you like to add additional remarks? (y/N): ")
if ret != "":
  while 1:
    ret = raw_input("Enter remark name: ")
    if ret =='':
      break
    else:
      num_remarks = num_remarks + 1
      CDDB_Info["NUMREMARKS"] = str(num_remarks)
      remname = ret
      ret = raw_input("Enter remark value: ")
      CDDB_Info["REMARK" + str(num_remarks-1)] = remname + "=" + ret
from CueParser import CueParser
cue = CueParser()
cue.getMetadataFromCDDB(disc_id, CDDB_Info)
filename = filename.replace('AlbumTitle',cue.title)
filename = filename.replace('AlbumYear',cue.year)
filename = filename.replace('AlbumPerformer',cue.performer)
cue.file = filename+'.flac'
cue.writeCUESheet(filename+'.cue')

if (chooseCover):
  jpgfilename = askopenfilename(filetypes=(('jpg Files', '*.jpg'),("All Files", "*")), title="Choose cover for " + cue.title)
  if jpgfilename:
    shutil.copy(jpgfilename, os.path.join(workingpath, filename + ".jpg"))

gotFLACFile = False
if (rip):
  #os.system("python ./secure_cdparanoia.py --force-cdrom-device "+ cddevice + " --force-read-speed 40 1- \"" + os.path.join(path, filename + ".wav") +"\"")
  os.system("cdparanoia --force-cdrom-device "+ cddevice + " --force-read-speed 40 1- \"" + os.path.join(workingpath, filename + ".wav") +"\"")
  print "encoding..."
  os.system("flac \"--output-name=" + os.path.join(workingpath, filename + ".flac") + "\" \"" + os.path.join(workingpath, filename + ".wav") + "\"")
  gotFLACFile = True
else:
  if (chooseFLAC):
    FLACFilename = askopenfilename(filetypes=(('FLAC Files', '*.flac'),("All Files", "*")), title="Choose FLAC File for " + cue.title)
    if (FLACFilename):
      shutil.copy(FLACFilename, os.path.join(workingpath, filename + ".flac"))
      gotFLACFile = True

if (gotFLACFile):
  print "writing tags..."
  os.system("python ./writeFLACTags.py \"" + os.path.join(workingpath, filename + ".cue") + "\"")
  print "moving..."
  shutil.copy(os.path.join(workingpath, filename + ".flac"), flacdir)
  os.unlink(os.path.join(workingpath, filename + ".flac"))
  if os.path.exists(os.path.join(workingpath, filename + ".wav")):
    os.unlink(os.path.join(workingpath, filename + ".wav"))

if (cuedir != ''):
  shutil.copy(os.path.join(workingpath, filename + ".cue"), cuedir)
  os.unlink(os.path.join(workingpath, filename + ".cue"))
  if os.path.exists(os.path.join(workingpath, filename + ".jpg")):
    shutil.copy(os.path.join(workingpath, filename + ".jpg"), cuedir)
    os.unlink(os.path.join(workingpath, filename + ".jpg"))
